package com.hspedu.qqserver.service;

import com.hspedu.qqcommon.Message;
import com.hspedu.qqcommon.MessageType;
import com.hspedu.qqcommon.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 王先锋
 * @version 1.0
 * 这是服务器，在监听9999，等待客户的连接，并保持通讯
 */
public class QQServer {
    private ServerSocket ss=null;
    //创建一个集合，存放多个用户，如果是这些用户登陆，就认为是合法
    private static ConcurrentHashMap<String,User> validusers=new ConcurrentHashMap<>();
    //
    private static ConcurrentHashMap<String, ArrayList<Message>> offLineDb=new ConcurrentHashMap<>();

    public static ConcurrentHashMap<String, ArrayList<Message>> getOffLineDb() {
        return offLineDb;
    }

    public static void setOffLineDb(ConcurrentHashMap<String, ArrayList<Message>> offLineDb) {
        QQServer.offLineDb = offLineDb;
    }

    static{//在静态代码块，初始化validusers
        validusers.put("100",new User("100","123456"));
        validusers.put("200",new User("200","123456"));
        validusers.put("300",new User("300","123456"));
        validusers.put("wxf",new User("wxf","123456"));
    }


    //离线用户登陆看是否需要发文件
    public void Rerevice(String userId){
        ArrayList<Message> messages = offLineDb.get(userId);
        if(messages!=null){
            for (Message me:messages) {
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(ManageClientThreads.getServerConnectClientThread(userId).getSocket().getOutputStream());
                  // me.setMesType
                    oos.writeObject(me);
                    offLineDb.remove(me);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    //验证用户是否有效的方法
    public boolean checkUser(String usrerId,String passwd){
        User user=validusers.get(usrerId);
        if(user==null){//说明userId没有存在validusers的key中
            return false;
        }
        if(!(user.getPasswd().equals(passwd))){//userId正确，密码错误
           return  false;
        }
        return true;
    }

    public QQServer( ) {
        System.out.println("服务器在9999端口监听..");
        try {

            //启动推送服务
            new Thread(new SendNewsToAllService()).start();
            ss=new ServerSocket(9999);
            while(true){
                Socket socket = ss.accept();//如果没有客户端连接阻塞于此
                //得到socket关联的对象输入流
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
               //得到socket关联的对象输出流
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                User u = (User)ois.readObject();
                Message message = new Message();
                //验证
                if(checkUser(u.getUserId(),u.getPasswd())){


                    //构建一个Messa对象，准备返回客户端
                    message.setMesType(MessageType.MESSAGE_LOGIN_SUCCEED);
                    //将message对象返回给客户端
                    oos.writeObject(message);
                    //创建一个线程和客户端保持通讯
                    ServerConnectClientThread serverConnectClientThread = new ServerConnectClientThread(socket, u.getUserId());
                    //启动线程
                    serverConnectClientThread.start();
                    //把改线程对象，放入到一个集合中
                    ManageClientThreads.addCilentThread(u.getUserId(),serverConnectClientThread);

                    //验证通过，看是否有离线需要传递
                    Rerevice(u.getUserId());
                }else{//登陆失效
                    message.setMesType(MessageType.MESSAGE_LOGIN_FAIL);
                   //失败返回这样对象
                    oos.writeObject(message);
                    //关闭资源
                    socket.close();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //如果服务端退出while循环，说明服务器不在监听，因此关闭ServerSocket
        }
    }
}
